package com.globallogic.oopbasics.competence.io;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Scanner;

import com.globallogic.oopbasics.competence.container.TotalCompetence;
import com.globallogic.oopbasics.competence.entity.Speciality;
import com.globallogic.oopbasics.competence.entity.SpecialityProfile;

public class SpecialityProfileScanner {

	private final File fFile;

	private List<SpecialityProfile> specialityProfiles;
	private List<Speciality> specialities;
	private TotalCompetence competenciesList;
	private TotalCompetence competenciesListForSpeciality;

	public List<SpecialityProfile> getSpecialityProfiles() {
		return specialityProfiles;
	}

	/** Template method that calls {@link #processLine(String)}. */
	public final void processLineByLine() throws FileNotFoundException,
			NoSuchElementException {
		Scanner scanner = new Scanner(new FileReader(fFile));
		try {
			if (!scanner.hasNextLine()) {
				throw new IllegalArgumentException(
						"Empty file. Unable to process.");
			} else {
				while (scanner.hasNextLine()) {
					processLine(scanner.nextLine());
				}
			}
		} finally {
			scanner.close();
		}
	}

	public SpecialityProfileScanner(String aFileName,
			List<Speciality> specialities, TotalCompetence competenciesList)
			throws FileNotFoundException, IllegalArgumentException,
			NoSuchElementException {
		this.specialities = specialities;
		this.competenciesList = competenciesList;
		init();
		fFile = new File(aFileName);
		processLineByLine();
	}

	protected void init() {
		specialityProfiles = new ArrayList<SpecialityProfile>();
	}

	/**
	 * Overridable method for processing lines in different ways.
	 */
	protected void processLine(String aLine) throws NoSuchElementException {
		// use a second Scanner to parse the content of each line
		Scanner scanner = new Scanner(aLine);
		scanner.useDelimiter("~");
		int specialityId = scanner.nextInt();
		competenciesListForSpeciality = new TotalCompetence();
		while (scanner.hasNext()) {

			int competencyId = scanner.nextInt();
			@SuppressWarnings("unused")
			String competencyName = scanner.next();
			@SuppressWarnings("unused")
			double competencyValue = scanner.nextDouble();
			competenciesListForSpeciality.add(competenciesList.getContainer()
					.get(competencyId - 1));
		}
		if (specialities.size() > 0) {
			specialityProfiles.add(new SpecialityProfile(specialities
					.get(specialityId - 1), competenciesListForSpeciality));
		}
	}
}
